﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Timers;
using System.Data.EntityClient;

namespace CalculateStatistics
{
    public partial class Service1 : ServiceBase
    {
        private System.Timers.Timer timer = new Timer();

        private EntityConnection entityConnection = null;

        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            #region Init connection
            EntityConnectionStringBuilder ecsb = new EntityConnectionStringBuilder();

            ecsb.Name = "DosvidEntities";

            entityConnection = new EntityConnection(ecsb.ConnectionString);

            entityConnection.Open();

            DAL.BAL.Business.Init(entityConnection);
            #endregion

            timer.Interval = 1000 * 60 * 60;

            timer.Elapsed += timer_Elapsed;

            timer.Enabled = true;

            EventLog.WriteEntry("Started");
        }

        protected override void OnStop()
        {
            timer.Enabled = false;

            entityConnection.Close();

            EventLog.WriteEntry("Stopped");
        }

        private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                timer.Enabled = false;

                DAL.BAL.Business.RefreshDayStatistics();
            }
            catch (Exception e1)
            {
                EventLog.WriteEntry(e1.Message, EventLogEntryType.Error);
            }
            finally
            {
                timer.Enabled = true;
            }

        }
    }
}
